#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>

void drawText(cv::Mat & image)
{
    putText(image, "Hello OpenCV",
            cv::Point(20, 50),
            cv::FONT_HERSHEY_COMPLEX, 1, // font face and scale
            cv::Scalar(255, 255, 255), // white
            1, cv::LINE_AA); // line thickness and type
}

int main()
{
    // rtsp地址变量
    //std::string rtsp_url = "rtsp://admin:srcb12345@10.0.0.157:554/stream/realtime?channel=1&streamtype=1";
    std::string rtsp_url = "rtsp://admin:Dai12345678@172.168.1.16:554/stream1";

    // CAP_FFMPEG：使用ffmpeg解码
    cv::VideoCapture stream1 = cv::VideoCapture(rtsp_url, cv::CAP_FFMPEG);

    if (!stream1.isOpened())
    {
        std::cout << "有视频流未打开" << std::endl;
        return -1;
    }

//    cv::VideoWriter writer = cv::VideoWriter("./rtsp-video.avi",
//                                        cv::CAP_GSTREAMER,
//                                         (int)stream1.get(cv::CAP_PROP_FOURCC),
//                                         (int)stream1.get(cv::CAP_PROP_FPS),
//                                         cv::Size((int)stream1.get(cv::CAP_PROP_FRAME_WIDTH),(int)stream1.get(cv::CAP_PROP_FRAME_HEIGHT)),
//                                         true
//                                         );
    cv::VideoWriter video("outcpp.avi", cv::VideoWriter::fourcc('M','J','P','G'), 24, cv::Size((int)stream1.get(cv::CAP_PROP_FRAME_WIDTH),(int)stream1.get(cv::CAP_PROP_FRAME_HEIGHT)));

//    if (!writer.isOpened()) {
//        std::cout << "create video failed!" << std::endl;
//        return 0;
//    }

    cv::Mat frame1;

    int width = (int)stream1.get(cv::CAP_PROP_FRAME_WIDTH);
    int height = (int)stream1.get(cv::CAP_PROP_FRAME_HEIGHT);
    cv::Mat frameBGR(height + height / 2, width, CV_8UC1);

    int count = 1;
    while (true)
    {
        if (!stream1.read(frame1))
        {
            std::cout << "有视频流未读取" << std::endl;
            continue;
        }

        drawText(frame1);
//        cv::imwrite(std::format("./test-{}.jpg", count),frame1);
        count++;


        // 设置窗口的初始大小
        cv::Size windowSize(1024, 768);

        // 创建窗口
        cv::namedWindow("Image Display", cv::WINDOW_AUTOSIZE);

        // 调整图像大小以适应窗口
        cv::resize(frame1, frame1, windowSize);

        // 显示图像
        cv::imshow("Image Display", frame1);

//        cv::imshow("rtsp_demo", frame1);


        //cv::cvtColor(frame1, frameBGR, cv::COLOR_RGB2BGR);
        //writer << frameBGR;

        // Write the frame into the file 'outcpp.avi'
        video.write(frame1);

        if (cv::waitKey(1) == 27)
        {
            break;
        }
    }

    return 0;
}
